import { defineStore } from "pinia";
import Task from "../entity/Task";
import TaskWrapper from "../entity/TaskWrapper";
import TaskStatusEnum from "../enumeration/TaskStatusEnum";
import { useBrowserStore } from "@/module/browser/store/BrowserStore";

export const useTaskStore = defineStore('task', {
    state: () => ({
        runList: new Array<TaskWrapper>(),
        successList: new Array<TaskWrapper>(),
        failList: new Array<TaskWrapper>(),
        cancelList: new Array<TaskWrapper>(),
        visible: false
    }),
    getters: {
        total: (state): number => state.runList.length,
        successTotal: (state): number => state.successList.length,
        failTotal: (state): number => state.failList.length,
        cancelTotal: (state): number => state.cancelList.length,
    },
    actions: {
        init() {
            // 初始化任务，100ms查看一次任务
            setInterval(() => this._daemon(), 100);
        },
        /**
         * 守护进程
         */
        _daemon() {
            // 此处处理并发量
            let runList = new Array<TaskWrapper>();
            for (let task of this.runList) {
                try {
                    switch (task.status) {
                        case TaskStatusEnum.RUN:
                            runList.push(task);
                            break;
                        case TaskStatusEnum.SUCCESS:
                            this.successList.push(task);
                            break;
                        case TaskStatusEnum.FAIL:
                            this.failList.push(task);
                            break;
                        case TaskStatusEnum.CANCEL:
                            this.cancelList.push(task);
                            break;
                    }
                } catch (e) {
                    console.error(e);
                }
            }
            this.runList = runList;
        },

        download(task: Task) {
            let wrapper = {
                ...task,
                createTime: new Date(),
                status: TaskStatusEnum.RUN,
                storageType: useBrowserStore().storage.type
            } as TaskWrapper
            task.run((progress, total) => {
                wrapper.total = total;
                wrapper.progress = progress;
            }, () => {
                wrapper.doneTime = new Date();
                wrapper.time = wrapper.doneTime.getTime() - wrapper.createTime.getTime();
                wrapper.status = TaskStatusEnum.SUCCESS
            }, () => {
                wrapper.doneTime = new Date();
                wrapper.time = wrapper.doneTime.getTime() - wrapper.createTime.getTime();
                wrapper.status = TaskStatusEnum.FAIL
            });
            this.runList.push(wrapper);
        },
        openTaskPanel() {
            this.visible = true;
        },
        closeTaskPanel() {
            this.visible = false;
        }
    }
})